<template>
  <div class="myCollect">

    <div class="search-box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="goBack">返回</el-button>
          <el-button type="default" @click="showCollectDialog">下载PDF</el-button>
        </el-form-item>
        <el-form-item label="批次">
          <!-- 理科 -->
          <el-select class="select-box" v-if="isScience" v-model="subjectType" placeholder="请选择">
            <el-option
                v-for="item in scienceOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
          <!-- 文科 -->
          <el-select class="select-box" v-if="isArts" v-model="subjectType" placeholder="请选择">
            <el-option
                v-for="item in liberalArts"
                :key="item.value"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="list-container">
      <el-table
          :data="schoolData"
          style="width: 100%;margin-bottom: 20px;"
          align="center"
          header-align="center"
          :row-key="getRowKeys"
          :expand-row-keys="expandsData"
          type="index"
          tooltip-effect="dark"
          @expand-change="getExpandsData"
          :row-class-name="tableRowClassName"
          v-loading="firLoading"
          border>
        <!-- 数据为空的缺省 -->
        <div slot="empty">
          暂无数据
        </div>
        <!-- 展开专业--开始 -->
        <el-table-column type="expand" class="testExpand">
          <template slot-scope="scope">
            <div>
              <el-table
                  v-if="scope.row.majorList && scope.row.majorList.length > 0"
                  :data="scope.row.majorList"
                  :row-key="getRowKeys"
                  tooltip-effect="dark"
                  :row-class-name="tableRowClassName"
                  :show-header="showHeader"
                  style="width: 100%;">

                <el-table-column
                    width="48">
                </el-table-column>
                <el-table-column
                    prop="code"
                    width="90"
                    label="代码">
                </el-table-column>
                <el-table-column
                    prop="majorName"
                    label="专业名称"
                    width="205">
                  <template slot-scope="scope">
                    <el-popover
                        placement="bottom-start"
                        width="750"
                        trigger="hover">
                      <div v-html="scope.row.majorDesc">
                      </div>
                      <div slot="reference">
                        {{scope.row.majorName}}
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="level"
                    width="80px"
                    label="层级">
                  <template slot-scope="scope">
                    <div>
                      {{scope.row.level=='无'?'':scope.row.level}}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    min-width="520"
                    prop="msg2015"
                    align="center"
                    label="2017/2018/2019 (计划)投档 | 最高分[位次] | 平均分 | 最低分[位次]">
                  <template slot-scope="scope">
                    <div class="file-section">
                      <div class="file-box" v-html="scope.row.msg2015"></div>
                      <div class="file-box" v-html="scope.row.msg2016"></div>
                      <div class="file-box" v-html="scope.row.msg2017"></div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    width="68"
                    prop="schoolName"
                    :label="(years+'').match(/.*(.{2})/)[1] + '计划'">
                  <div v-if="scope.row.plan2018 > 0"
                       :class="{colorMain: scope.row.planStatus2018==0, colorGreen: scope.row.planStatus2018==1}">
                    {{scope.row.planStatus2018==1?'↑':(scope.row.planStatus2018==2?'':'↓')}}{{scope.row.plan2018}}
                  </div>
                  <div v-if="scope.row.plan2018 == 0">{{scope.row.plan2018}}</div>
                </el-table-column>
                <el-table-column
                    width="88"
                    label="操作">
                  <template slot-scope="scope">
                    <div class="colorMain cancel" @click="cancelUtil(scope.row, 'major')">取消收藏</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <!-- 展开专业--结束 -->

        <el-table-column
            prop="code"
            width="90"
            label="代码">
        </el-table-column>
        <el-table-column
            prop="schoolName"
            label="院校名称"
            width="150">
          <template slot-scope="scope">
            <el-popover
                placement="bottom-start"
                width="750"
                trigger="hover">
              <div v-html="scope.row.describe">
              </div>
              <div slot="reference">
                {{scope.row.schoolName}}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
            prop="sortNum"
            width="55"
            label="排名">
        </el-table-column>
        <el-table-column
            min-width="480"
            prop="msg2015"
            align="center"
            label="2017/2018/2019 计划/投档|最低分|最低线差|最低位次">
          <template slot-scope="scope">
            <div class="file-section">
              <div class="file-box" v-html="scope.row.msg2015"></div>
              <div class="file-box" v-html="scope.row.msg2016"></div>
              <div class="file-box" v-html="scope.row.msg2017"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="manager"
            label="主管单位">
          <template slot-scope="scope">
            <div>{{scope.row.manager.length>4?scope.row.manager.substr(0, 4):scope.row.manager}}</div>
          </template>
        </el-table-column>
        <el-table-column
            prop="city"
            label="所在地区">
          <template slot-scope="scope">
            <div>{{scope.row.city.name}}</div>
          </template>
        </el-table-column>
        <el-table-column
            prop="level"
            label="层级属性">
          <template slot-scope="scope">
            <div>{{scope.row.level.name}}</div>
          </template>
        </el-table-column>
        <el-table-column
            prop="majorPlan"
            label="专业安排">
          <template slot-scope="scope">
            <div>{{scope.row.majorPlan}}</div>
          </template>
        </el-table-column>
        <el-table-column
            width="70"
            prop="majorPlan"
            :label="(years+'').match(/.*(.{2})/)[1] + '计划'">
          <template slot-scope="scope">
            <div v-if="scope.row.plan2018 > 0"
                 :class="{colorMain: scope.row.planStatus2018==0, colorGreen: scope.row.planStatus2018==1}">
              {{scope.row.planStatus2018==1?'↑':(scope.row.planStatus2018==2?'':'↓')}}{{scope.row.plan2018}}
            </div>
            <div v-if="scope.row.plan2018 == 0">{{scope.row.plan2018}}</div>
          </template>
        </el-table-column>
        <el-table-column
            width="88"
            label="操作">
          <template slot-scope="scope">
            <div class="colorMain cancel" @click="cancelUtil(scope.row, 'school')">取消收藏</div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 导出弹窗 -->
    <div v-show="dialogCollect" class="collect-dialog">

      <div class="dialog-container">
        <div class="data-container" id="listContainer" ref="listContainer">
          <div class="pdf-header" id="pdfHeader">
            <img class="mendao-logo" src="@/assets/images/mendao-logo.png" alt="logo">
            <div class="pdf-title">
              门道数据查询系统
            </div>
          </div>
          <el-table
              :data="schoolData"
              style="width: 100%;margin-bottom: 20px;"
              align="center"
              header-align="center"
              :row-key="getRowKeys"
              :expand-row-keys="expandsData"
              type="index"
              tooltip-effect="dark"
              @expand-change="getExpandsData"
              :row-class-name="tableRowClassName"
              v-loading="firLoading"
              border>
            <!-- 数据为空的缺省 -->
            <div slot="empty">
              暂无数据
            </div>
            <!-- 展开专业--开始 -->
            <el-table-column type="expand" class="testExpand">
              <template slot-scope="scope">
                <div>
                  <el-table
                      v-if="scope.row.majorList && scope.row.majorList.length > 0"
                      :data="scope.row.majorList"
                      :row-key="getRowKeys"
                      tooltip-effect="dark"
                      :row-class-name="tableRowClassName"
                      :show-header="showHeader"
                      style="width: 100%;">

                    <el-table-column
                        width="48">
                    </el-table-column>
                    <el-table-column
                        prop="code"
                        width="80"
                        label="代码">
                    </el-table-column>
                    <el-table-column
                        prop="majorName"
                        label="专业名称"
                        width="160">
                      <template slot-scope="scope">
                        <el-popover
                            v-if="scope.row.majorDesc"
                            placement="bottom-start"
                            width="600"
                            trigger="hover">
                          <div v-html="scope.row.majorDesc">
                          </div>
                          <div slot="reference">
                            {{scope.row.majorName}}
                          </div>
                        </el-popover>
                        <div class="cursor-type" v-else>{{scope.row.majorName}}</div>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="msg2015"
                        align="center"
                        label="2017/2018/2019 (计划)投档 | 最高分[位次] | 平均分 | 最低分[位次]">
                      <template slot-scope="scope">
                        <div class="file-section">
                          <div class="file-box" v-html="scope.row.msg2015"></div>
                          <div class="file-box" v-html="scope.row.msg2016"></div>
                          <div class="file-box" v-html="scope.row.msg2017"></div>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <!-- 展开专业--结束 -->

            <el-table-column
                prop="code"
                width="80"
                label="代码">
            </el-table-column>
            <el-table-column
                prop="schoolName"
                label="院校名称"
                width="160">
              <template slot-scope="scope">
                <el-popover
                    v-if="scope.row.describe"
                    placement="bottom-start"
                    width="600"
                    trigger="hover">
                  <div v-html="scope.row.describe">
                  </div>
                  <div slot="reference">
                    {{scope.row.schoolName}}
                  </div>
                </el-popover>
                <div class="cursor-type" v-else>{{scope.row.schoolName}}</div>
              </template>
            </el-table-column>
            <el-table-column
                prop="msg2015"
                align="center"
                label="2017/2018/2019 计划/投档|最低分|最低线差|最低位次">
              <template slot-scope="scope">
                <div class="file-section">
                  <div class="file-box" v-html="scope.row.msg2015"></div>
                  <div class="file-box" v-html="scope.row.msg2016"></div>
                  <div class="file-box" v-html="scope.row.msg2017"></div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="dialog-footer">
          <el-button type="default" @click="closeCollectDialog">关闭</el-button>
          <el-button type="primary" @click="printCollectList">下载PDF</el-button>
        </div>
      </div>


    </div>

  </div>
</template>

<script>
  import API from '@assets/js/api.js'

  import html2canvas from 'html2canvas'
  import jsPDF from '@assets/js/jspdf.min.js'

  export default {
    name: "myCollect",
    data() {
      return {
        years: 0,
        scienceOptions: [
          {
            name: '理工类一本',
            value: 1
          },
          {
            name: '理工类二本',
            value: 3
          },
          {
            name: '理工类高职专科',
            value: 7
          },
        ],
        liberalArts: [
          {
            name: '文史类一本',
            value: 2
          },
          {
            name: '文史类二本',
            value: 4
          },
          {
            name: '文史类高职专科',
            value: 8
          },
        ],
        isArts: false,
        isScience: false,
        subjectType: "",
        schoolData: [],
        expandsData: [],
        majorData: [],
        firLoading: false,
        showHeader: true,
        userInfo: {},
        currentExpandCode: "",
        pdf: null,
        dialogCollect: false,
      }
    },
    created() {
      // 获取当前时间
      this.years = new Date().getFullYear();
      if(sessionStorage.getItem('userInfo')) {
        this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        this.typeUtil()
      }
      // this.getCollectData();
    },
    mounted() {

    },
    methods: {
      typeUtil() {
        if(this.userInfo.type == 1) {
          this.isScience = true;
          this.subjectType = this.scienceOptions[0].value;
        } else {
          this.isArts = true;
          this.subjectType = this.liberalArts[0].value;
        }
      },
      getCollectData() {
        let params = {
          type: this.subjectType
        };
        this.axios.post(API.queryCollectList, params).then(res => {
          if (res.data.code === 1) {
            this.schoolData = res.data.list;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(err => {
          this.$message.error(err);
        })
      },
      getRowKeys(row) {
        return row.code;
      },
      getExpandsData(row, expandedRows) {
        this.currentExpandCode = row.code
      },
      // 判断是否展示子集箭头
      tableRowClassName(row) {
        let res = '';
        if (!row.row.majorList || row.row.majorList.length == 0) {
          res = 'row-expand-cover';
        }
        return res;
      },
      // 取消收藏
      cancelUtil(row, type) {
        // http://localhost:8081/api/mendao/canelUserCollect?type=2&schoolCode=1001&majorCode=
        // http://localhost:8081/api/mendao/canelUserCollect?type=2&schoolCode=1001&majorCode=
        let params = {
          type: row.type,
          schoolCode: row.code,
        };
        let urlParams ='?type=' + params.type + '&schoolCode=' + params.schoolCode;
        if (type === 'major') {
          params = {
            type: row.type,
            schoolCode: this.currentExpandCode,
            majorCode: row.majorCode,
          };
          urlParams += '&majorCode=' + params.majorCode;
        }



        this.axios.get(API.cancelCollect + urlParams).then(res => {
          if (res.data.code === 1) {
            this.$message.success("取消收藏！");
            this.getCollectData();
          } else {
            this.$message.error("取消收藏失败！");
          }
        }).catch(err => {
          this.$message.error(err);
        })
      },
      goBack() {
        this.$router.go(-1);
      },
      // 展开分类
      schoolExpand() {
        // 循环把需要展开的放进去
        this.schoolData.forEach(item => {
          if (item.majorList && item.majorList.length > 0) {
            this.expandsData.push(item.code);
          }
        });
      },

      showCollectDialog() {
        this.dialogCollect = true;
      },
      closeCollectDialog() {
        this.dialogCollect = false;
      },

      // 打印页面
      printCollectList() {
        this.schoolExpand();
        setTimeout(() => {
          // 生成pdf
          this.pdf = this.$refs.listContainer;
          let target = this.pdf;
          // return false
          html2canvas(target, {
            allowTaint: true,
            useCORS: true, // 当图片是链接地址时，需加该属性，否组无法显示图片
            "imageTimeout": 0,
            'scale': 2,
          })
            .then(canvas => {

              /**jspdf将html转为pdf一页显示不截断，整体思路：
               * 1. 获取DOM
               * 2. 将DOM转换为canvas
               * 3. 获取canvas的宽度、高度（稍微大一点）
               * 4. 将pdf的宽高设置为canvas的宽高
               * 5. 将canvas转为图片
               * 6. 实例化jspdf，将内容图片放在pdf中（因为内容宽高和pdf宽高一样，就只需要一页，也防止内容截断问题）
               */

                // 得到canvas画布的单位是px 像素单位
              let contentWidth = canvas.width;
              let contentHeight = canvas.height;

              //一页pdf显示html页面生成的canvas高度;
              let pageHeight = contentWidth / 592.28 * 841.89;
              //未生成pdf的html页面高度
              let leftHeight = contentHeight;
              //页面偏移
              let position = 0;
              //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
              let imgWidth = 595.28;
              let imgHeight = 592.28 / contentWidth * contentHeight;

              // 将canvas转为base64图片
              let pageData = canvas.toDataURL('image/jpeg', 1.0)

              // 初始化jspdf 第一个参数方向：默认''时为纵向，第二个参数设置pdf内容图片使用的长度单位为pt，第三个参数为PDF的大小，单位是pt
              // let PDF = new jsPDF('', 'pt', [pdfX, pdfY])
              let PDF = new jsPDF('', 'pt', 'a4')

              //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
              //当内容未超过pdf一页显示的范围，无需分页
              if(leftHeight < pageHeight) {
                // 将内容图片添加到pdf中，因为内容宽高和pdf宽高一样，就只需要一页，位置就是 0,0
                // PDF.addImage(pageData, 'jpeg', 0, 0, imgX, imgY);
                PDF.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28 / canvas.width * canvas.height);
              } else {
                while(leftHeight > 0) {
                  //arg3-->距离左边距;arg4-->距离上边距;arg5-->宽度;arg6-->高度
                  PDF.addImage(pageData, 'JPEG', 0, position,imgWidth, imgHeight)

                  leftHeight -= pageHeight;
                  position -= 841.89;
                  //避免添加空白页
                  if(leftHeight > 0) {
                    //注②
                    PDF.addPage();
                  }
                }
              }

              PDF.save('我的收藏.pdf')
              this.expandsData = [];

            });

        }, 1000)
      },


    },
    watch: {
      subjectType() {
        this.getCollectData();
      }
    }
  }
</script>

<style lang="stylus">
  .myCollect
    .el-table--scrollable-x .el-table__body-wrapper
      overflow-x: hidden;

    .el-table__expanded-cell[class*=cell]
      padding: 0 !important;

    .el-table--enable-row-hover .el-table__body tr:hover>td
      background-color: rgba(255, 255, 255, 0) !important;

    .row-expand-cover .el-table__expand-column .el-table__expand-icon
      display: none;

    .th-center
      text-align center

</style>
<style scoped lang="stylus">
  $theme-color = #E65A1E
  $theme-txt = #ED8B61

  .myCollect
    width 100%

    .search-box
      width 100%
      padding-top 15px

      .level-tag
        margin-right 6px
        cursor pointer

        &.active
          background-color: $theme-txt;
          border-color: $theme-txt;
          color: #fff;

    .pdf-header
      display flex
      align-items center
      padding 20px 40px

      .mendao-logo
        width 80px

        img
          width 100%

      .pdf-title
        padding-left 30px
        font-family SourceHanSansCN-Medium
        font-size 20px
        font-weight 500
        color #333

    .file-section
      display flex
      flex-wrap nowrap

      .file-box
        position relative
        flex 1
        padding 0 5px
        text-align right

      .file-box:before
        position absolute
        content: ' '
        top 0
        right 0
        z-index 2
        margin-top -12px
        width 1px
        height 50px
        background #EBEEF5

      .file-box:last-child:before
        background rgba(255, 255, 255, 0)

    .cancel
      cursor pointer


    .collect-dialog
      position fixed
      top 0
      left 0
      bottom 0
      z-index 100
      width 100%
      padding 0 30px
      background rgba(0, 0, 0, 0.5)

      .dialog-container
        position relative
        width 70%
        max-height 80%
        overflow-y scroll
        margin 0 auto
        padding 30px 40px
        top 50%
        transform translate(0, -50%)
        background #fff
        border-radius 4px
        .data-container
          padding 20px 30px 50px 20px
        .dialog-footer
          padding-bottom 30px
          text-align center


    .colorMain
      color: $theme-color !important;

    .colorGreen
      color: #3CB371 !important;

    .colorYellow
      color #E6A23C !important

    .bgYellow
      background #E6A23C !important

    .cursor-type
      cursor pointer
</style>